package top.zdkhqh.bean;

import top.zdkhqh.FileUtil;
import top.zdkhqh.ImageUtil;

import java.awt.*;
import java.io.File;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author HuangQihan
 * @date 2019/9/10
 */

public class PictureGallery {
    /**
     * <文件名称，使用次数>
     */
    private Map<String, Integer> picUsedCountMap;
    /**
     * <RGB值，文件名称>
     */
    private Map<Integer, String> rgbValueMap;

    /**
     * 图片张树
     */
    private Integer size;

    /**
     * 每张图片出现次数限制,为null时不限制
     */
    private Integer limit;

    private List<String> smallPath;

    public PictureGallery(String url, int size, int limit) {
        this.size = size;
        this.limit = limit;

        picUsedCountMap = new HashMap<>();
        rgbValueMap = new HashMap<>();

        smallPath = FileUtil.getAllFileName(url, size).stream()
                .map(e -> url + File.separator + e)
                .collect(Collectors.toList());
        new HashSet<>(smallPath).forEach(s -> {
            rgbValueMap.put(ImageUtil.getAverageRGB(s), s);
        });
    }


    /**
     * @param color 源
     * @return
     */
    public String getMostSimilar(Color color) {
        double similar = Double.MAX_VALUE;
        Integer key = null;
        for (Integer e : rgbValueMap.keySet()) {
            double similarResult = getColorSemblance(color, new Color(e));
            if (similarResult < similar) {
                if (limit == null || picUsedCountMap.getOrDefault(rgbValueMap.get(e), 0) <= limit) {
                    similar = similarResult;
                    key = e;
                }

            }
        }
        String result = rgbValueMap.get(key);

        int count = picUsedCountMap.getOrDefault(result, 0) + 1;
        picUsedCountMap.put(result, count);

        return result;
    }

    public Integer getSize() {
        return size;
    }

    public List<String> getSmallPath() {
        return smallPath;
    }

    public Map<String, Integer> getPicUsedCountMap() {
        return picUsedCountMap;
    }

    public void setPicUsedCountMap(Map<String, Integer> picUsedCountMap) {
        this.picUsedCountMap = picUsedCountMap;
    }

    public Map<Integer, String> getRgbValueMap() {
        return rgbValueMap;
    }

    public void setRgbValueMap(Map<Integer, String> rgbValueMap) {
        this.rgbValueMap = rgbValueMap;
    }

    /**
     * rgb值相似度比较
     *
     * @param color1
     * @param color2
     * @return 值越大，相似度越小；值越小，相似度越大
     */
    public static double getColorSemblance(Color color1, Color color2) {
        double rD = (color1.getRed() - color2.getRed()) / 256.0;
        double gD = (color1.getGreen() - color2.getGreen()) / 256.0;
        double bD = (color1.getBlue() - color2.getBlue()) / 256.0;
        return Math.sqrt(rD * rD + gD * gD + bD * bD);
    }

}
